import { baseURL, debouncedToLogin } from "./request";

/**
 * OSS文件上传
 * @param {string} filePath - 文件路径
 * @param {string} extname - 文件扩展名
 * @param {string} dir - 上传目录
 * @returns {Promise} 返回上传结果Promise
 */
export const uploadFile = (filePath, extname, dir) => {
    return new Promise((resolve, reject) => {
        try {
            // 获取token
            const token = uni.getStorageSync('token');
            if (!token) {
                uni.showModal({
                    title: '登录',
                    content: '请登录',
                    showCancel: false,
                    confirmText: '去登录',
                    success: ({ confirm }) => {
                        if (confirm) {
                            if (getCurrentPages()[getCurrentPages().length - 1].route == 'pages/login/index') {
                                return;
                            } else {
                                debouncedToLogin();
                            }
                        }
                    }
                });
                reject(new Error('未登录'));
                return;
            }

            const upTask = uni.uploadFile({
                url: `${baseURL}/addons/alioss/index/upload?isApi=1`,
                filePath: filePath,
                name: 'file',
                formData: {
                    extname: extname || '',
                    dir: dir || 'default'
                },
                header: {
                    'token': token
                },
                // #ifdef MP-ALIPAY
                fileType: 'image',
                // #endif
                success: (uploadRes) => {
                    try {
                        const result = JSON.parse(uploadRes.data);
                        // 根据实际接口返回格式调整判断条件
                        if (result.code === 0) { // code为0表示失败
                            // 如果是未登录错误，跳转到登录页
                            if (result.msg.includes('登录')) {
                                uni.navigateTo({
                                    url: '/pages/login/index'
                                });
                            }
                            uni.showToast({
                                title: result.msg || '上传失败',
                                icon: 'none'
                            });
                            reject(new Error(result.msg || '上传失败'));
                            return;
                        }
                        resolve(result.data);
                    } catch (e) {
                        uni.showToast({
                            title: '上传结果解析失败',
                            icon: 'none'
                        });
                        reject(new Error('上传结果解析失败'));
                    }
                },
                fail: (error) => {
                    uni.showToast({
                        title: '上传失败，请重试',
                        icon: 'none'
                    });
                    reject(error);
                }
            });

            // 监听上传进度
            upTask.onProgressUpdate((res) => {
                if (typeof onProgress === 'function') {
                    onProgress(res.progress);
                }
            });
        } catch (error) {
            uni.showToast({
                title: '上传初始化失败',
                icon: 'none'
            });
            reject(error);
        }
    });
};

/**
 * 批量上传文件
 * @param {Array} files - 文件路径数组
 * @param {string} dir - 上传目录
 * @returns {Promise} 返回上传结果Promise
 */
export const uploadFiles = async (files, dir) => {
    try {
        const results = await Promise.all(
            files.map(file => {
                const extname = file.substring(file.lastIndexOf('.') + 1);
                return uploadFile(file, extname, dir);
            })
        );
        return results;
    } catch (error) {
        uni.showToast({
            title: '批量上传失败',
            icon: 'none'
        });
        throw error;
    }
};


// 图片错误
export const imgError = (e) => {
    console.log(e);
    e.target.src = '/static/icon/error.png';
}

// 跳转
export const skip = (url, type = 'navigateTo') => {
    try {
        if (type === 'navigateTo') {
            uni.navigateTo({ url });
        } else {
            uni.redirectTo({ url });
        }
    } catch (error) {
        uni.showToast({
            title: '跳转失败',
            icon: 'none'
        });
    }
}


// 复制
export const copy = (text) => {
    try {
        uni.setClipboardData({
            data: text
        });
    } catch (error) {
        uni.showToast({ title: '复制失败', icon: 'none' });
    }
}


// 判断是否为空
export const isAllEmpty = (obj) => {
    // null 或 undefined
    if (obj === null || obj === undefined) return true;
    // 空字符串
    if (typeof obj === 'string' && obj.trim() === '') return true;
    // 空数组
    if (Array.isArray(obj) && obj.length === 0) return true;
    // 空对象
    if (typeof obj === 'object' && !Array.isArray(obj) && Object.keys(obj).length === 0) return true;
    return false;
}